package com.ideal.hadoopadmin.service.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.common.framework.orm.SearchFilter;
import com.ideal.hadoopadmin.entity.report.FairSchedulerAllocation;
import com.ideal.hadoopadmin.entity.system.Role;
import com.ideal.hadoopadmin.entity.system.UserRole;
import com.ideal.hadoopadmin.mapper.webdb.report.FairSchedulerAllocationMapper;
import com.ideal.hadoopadmin.mapper.webdb.system.RoleMapper;
import com.ideal.hadoopadmin.mapper.webdb.system.UserRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by fwj on 2016/3/3.
 * 队列资源访问报表
 */
@Service
public class RoleService {

    private static Logger logger = LoggerFactory.getLogger(RoleService.class);

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    public PageInfo queryRoleList(Map<String, Object> searchParams, HttpServletRequest request) {
        int currentPage = Integer.parseInt(request.getParameter("page") == null ? "1" : request.getParameter("page"));
        //过滤器
        String where = SearchFilter.parseToString(searchParams);
        //使用分页
        PageHelper.startPage(currentPage, 10);
        //加入组织好的where 条件
        PageHelper.setAppendWhere(where);
        List<Role> metaHdfsInfoList = roleMapper.queryRoleList();
        PageInfo pageInfo = new PageInfo(metaHdfsInfoList);
        return pageInfo;
    }

    /**
     * 根据id查询
     */
    public Role queryRoleById(Long id) {
        return roleMapper.queryRoleById(id);
    }

    public void saveRole(Role role) {
        roleMapper.saveRole(role);
    }

    public void updateRole(Role role) {
        roleMapper.updateRole(role);
    }

    public String deleteeRoleByID(Long[] ids) {
        //当进行批量删除时，将用户正在使用的角色得到
        String errorMessage = "";
        for (int i = 0; i < ids.length; i++) {
            Role role = roleMapper.queryRoleById(ids[i]);
            if (role != null) {
                //判断该角色是否在用户管理里面选择该角色，如果已经被使用，则不能删除。
                List<UserRole> userRoleList = userRoleMapper.queryUserRoleByRoleId(ids[i]);
                if (userRoleList.size() > 0) {
                    errorMessage += role.getName() + ",";
                } else {
                    roleMapper.deleteeRoleByID(ids[i]);
                }
            }
        }
        return errorMessage;
    }

    /**
     * 查询全部
     */
    public List<Role> queryRoleAllList() {
        List<Role> roleList = roleMapper.queryRoleList();
        return roleList;
    }
}
